package uk.co.cocking.getinline2;

import org.apache.log4j.Logger;

import uk.co.cocking.getinline2.exceptions.EnvironmentException;
import uk.co.cocking.getinline2.pipeline.Consumer;

public class Runner<IncomingType> {

	private static final int OK = 0;
	private static final int FAILED = -1;
	private final Consumer<IncomingType> consumer;
	private static Logger log = Logger
			.getLogger("uk.co.cocking.getinline2.Runner");

	public Runner(Consumer<IncomingType> sink) {
		this.consumer = sink;
	}

	public int run(IncomingType... items) {
		log.info(Version.versionString());
		log.info("Starting run");
		int returnCode = OK;
		try {
			consumer.open();
			consumer.process(items);
		} catch (Exception e) {
			log.error("run failed", e);
			returnCode = FAILED;
		}
		try {
			consumer.close();
			log.info("Ending run");
		} catch (EnvironmentException e1) {
			log.error("could not close pipeline: ", e1);
			returnCode = FAILED;
		} catch (Exception e2) {
			log.error("uncaught exception during run:", e2);
			returnCode = FAILED;
		}
		return returnCode;
	}
}
